package core.utils;

import core.io.Request;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 静态资源获取与读取
 * @author wsz
 * @date 2021/11/12 17:41
 **/
public class StaticResourceUtil {

    /**
     * 根据请求对象获取对应的静态资源路径，需要传递appBase
     * @param request
     * @return
     */
    public static String getAbsolutePath(Request request) {
        String path = request.getUrl();
        try {
            File file = new File("");
            // TODO 需要知道appBase
            String solutePath = file.getCanonicalPath() + "/" + request.getAppBase();
            return solutePath.replaceAll("\\\\", "/") + path;
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException("cannot found static resource: path=" + path);
        }
    }

    /**
     * 获取静态资源的绝对路径
     * @param path
     * @return
     */
    public static String getAbsolutePath(String path) {
        try {
            String solutePath = StaticResourceUtil.class.getResource("/").getPath();
            return solutePath.replaceAll("\\\\", "/") + path;
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException("cannot found static resource: path=" + path);
        }
    }

    /**
     * 读取静态资源文件输入流，封装到输出流
     * @param inputStream
     * @param outputStream
     */
    public static void outputStaticResource(InputStream inputStream, OutputStream outputStream) throws IOException {
        int count = 0;
        while (count == 0) {
            count = inputStream.available();
        }
        // Http请求头
        outputStream.write(HttpProtocolUtil.getHttpHeader200(count).getBytes());
        // 流转换
        long written = 0;
        int byteSize = 1024;
        byte[] buffer = new byte[byteSize];
        while (written < count) {
            if (written + byteSize > count) {
                byteSize = (int) (count - written);
                buffer = new byte[byteSize];
            }
            inputStream.read(buffer);
            outputStream.write(buffer);
            outputStream.flush();
            written += byteSize;
        }
    }

}
